$(function(){
    //设备详情窗口
    $('#show_details').dialog({
        title:'设备详情',
        width:840,
        height:420,
        modal:true,
        closed:true
    });

    //任务窗口
    $('#task_dg').dialog({
        title:'添加',
        width:800,
        height:420,
        modal:true,
        closed:true,
        buttons:[{
            text:'确定',
            iconCls:'icon-ok',
            handler:okHandler
        },{
            text:'取消',
            handler:function(){
                $('#task_dg').dialog('close');
            }
        }]
    });

    //任务窗口
    $('#device_route_dg').dialog({
        title:'光路拓扑',
        width:980,
        height:420,
        modal:true,
        closed:true,
        buttons:[{
            text:'关闭',
            handler:function(){
                $('#device_route_dg').dialog('close');
            }
        }]
    });

    $('#terminal_clientuser_dg').dialog({
        title:'端子用户',
        width:640,
        height:300,
        modal:true,
        closed:true
    });

    $('#terminal_clientuser_tb').datagrid({
        nowrap: false,
        singleSelect:true,
        pagination:true,
        idField:'id',
        frozenColumns:[[
            {title:'名称',field:'text',width:200,
                formatter:function(value){
                    return '<span style="color:red">'+value+'</span>';
                }
            }
        ]],
        columns:[[
            {field:'vip',title:'是否vip',width:250},
            {field:'type',title:'业务类型',width:250}
        ]]
    });

    $(".select-device-net").live("click",function(){
        var form = $("form.add_terminal_form");
        var tf = form.find("input[name='terId']");
        var id = form.find("input[name='id']");
        var number = form.find("input[name='number']");
        if(!id || id.val()==''){
            $.messager.alert('提示','没有编辑端子信息，无法查看光路！','info');
            return;
        }
        if(!tf || tf.val()==''){
            $.messager.alert('提示','参数错误','info');
            return;
        }
        var terid= tf.val();
        if(!terid){
            $.messager.alert('提示','参数错误','info');
            return;
        }
        var url = $("#routeUrl").val();
        var deviceId = $('.select-composition').data("deviceId");
        url += "?id="+deviceId+"&terid="+terid+"&number="+number.val()+"&r="+Math.random();
        $('#device_route_ifr').attr("src",url)
        $('#device_route_dg').dialog("open")
    })  ;



    $(".select-device-terminal-clientuser").live("click",function(){
        var form = $("form.add_terminal_form");
        var tf = form.find("input[name='terId']");
        var id = form.find("input[name='id']");
        if(!id || id.val()==''){
            $.messager.alert('提示','没有编辑端子信息，无法添加用户！','info');
            return;
        }
        if(!tf || tf.val()==''){
            $.messager.alert('提示','参数错误','info');
            return;
        }
        var terid= tf.val();
        if(!terid){
            $.messager.alert('提示','参数错误','info');
            return;
        }
        var deviceId = $('.select-composition').data("deviceId");
        $("#terminal_clientuser_tb").data("terminalId",terid);
        $('#terminal_clientuser_tb').datagrid({url:$("#terminalClientUserUrl").val()+"?id="+terid+"&deviceId="+deviceId+"&r="+Math.random()});
        $('#terminal_clientuser_dg').dialog("open");
    })

    //任务的指派时间
    $('#assignDate').datebox({
        required:true
    });

    //设备窗口中的标签
    $('#show_details_tab').tabs({
        onSelect:function(title){
            if(title == '地理位置') {
                initMap()
            }
            /*if(title == '任务管理') {
                task();
            }*/

        }
    });

   /* //设备选择模板
    $('#cc').combotree({
        onSelect:function(node){
            if(!node){
                return;
            }
             var id = node.id;
            if(!id){
                return;
            }
            id = ""+id;
            if(id.indexOf('-') != -1) {
                $.messager.alert('提示','请选择正确的模板','info');
                $('#cc').combotree('clear')
                return;
            }
            _loadFormwork(id);
        } ,onShowPanel:function(){
            $('#cc').combotree('reload');
        }
    }) ;*/

    //设备选择模板
    $('#client_combo').combotree({
        onSelect:function(node){
            var id = node.id;
            id = ""+id;
            if(id.indexOf('@') != -1) {
                $.messager.alert('提示','请选择通信用户','info');
                $('#client_combo').combotree('clear');
                return false;
            }
        } ,onShowPanel:function(){
            $('#client_combo').combotree('reload');
        }
    })
    $(".terminal_clientuser_tb_save").live("click",function(){
        var deviceId = $('.select-composition').data("deviceId");
        var terId = $("#terminal_clientuser_tb").data("terminalId");
        if(!deviceId || !terId){
            return;
        }
        var cuId = $('#client_combo').combotree("getValue");
        var url = $("#saveTerminalClientUserUrl").val();
        $.post(url,{id:cuId,terId:terId,deviceId:deviceId},function(data){
             if(data.status == '1'){
                 $.messager.alert('提示','用户添加成功','info');
                 $('#terminal_clientuser_tb').datagrid("reload");
                 return;
             }else if(data.status == '2'){
                 $.messager.alert('提示',"用户添加失败,已经绑定设备"+data.deviceName+"端子"+data.terId,'info');
                 return;
             }else if(data.status == '3'){
                 $.messager.alert('提示','用户添加失败,已经绑定当前端子','info');
                 return;
             }
            $.messager.alert('提示','用户添加失败','info');
        },'json')

    })  ;
    $(".terminal_clientuser_tb_del").live("click",function(){
        var cuId = $("#terminal_clientuser_tb").datagrid("getSelected");
        if(!cuId){
            $.messager.alert('提示','请选择用户','info');
            return;
        }
        $.messager.confirm('提示','确定删除该用户？',function(t){
            if(t){
                deleteTermainClientUser()
            }
        });
    }) ;
    function deleteTermainClientUser(){
        var deviceId = $('.select-composition').data("deviceId");
        var terId = $("#terminal_clientuser_tb").data("terminalId");
        var cuId = $("#terminal_clientuser_tb").datagrid("getSelected");
        if(!cuId){
            $.messager.alert('提示','请选择用户','info');
            return;
        }
        cuId = cuId.id;
        var url = $("#deleteTerminalClientUserUrl").val();
        $.post(url,{id:cuId,terId:terId,deviceId:deviceId},function(data){
            if(data.status == '1'){
                $.messager.alert('提示','用户删除成功','info');
                $('#terminal_clientuser_tb').datagrid("reload");
                return;
            }
        },'json');
    }

    $("#add_terminal_form select[name='backboneWiring']").live("change",function(){
        var t = $(this);
        var tv = t.val();
        if(tv == 'BACKBONE') {
           // $("#add_terminal_form .superior-terminal").show();
        } else{
           // $("#add_terminal_form .superior-terminal").hide();
        }
    })  ;

    $("#add_terminal_form input[name='splitter']").live("change",function(){
        var t = $(this);
        if(t.attr("checked")){
            $("#add_terminal_form .splitter-chk").show();
        } else{
            $("#add_terminal_form .splitter-chk").hide();
        }
    }) ;

    $(".select-device-terminal-edit").live("click",function(){
        var splitterChk =  $("#add_terminal_form input[name='splitter']");
        if(splitterChk.attr("checked")) {
            $("#add_terminal_form .splitter-chk").show();
        } else{
            $("#add_terminal_form .splitter-chk").hide();
        }
        $("#terminal_detail_container #add_terminal_form").show();
        $("#terminal_detail_container #device_terminal_show_container").hide();
    })


    //模板ID加载模板
    function _loadFormwork(id) {
        var f = $('.select-composition').data(id) ;
        if(f) {
            build(f);
            return;
        }
        var url = $('#formworkUrl').val();
        $.getJSON(url,{id:id,r:Math.random()},function(data){
            $('.select-composition').data(id,data) ;
            build(data);
        })
    }

    //端子标签中树形点击事件，A面id为a0,选择A面1区id为a1，A面2区为a2...
    function treeNodeClick(id) {
        $("#terminal_detail_container").empty();
       // $("#terminal_detail_container #device_terminal_show_container").show();
        if(id == 'all') { //事件布局
            $('#show_details_terminal_formwork').show();
            $('#show_details_terminal_content').hide();

            return;
        }
        $('#show_details_terminal_formwork').hide();
        $('#show_details_terminal_content').show();
        if(id == 'a0') {//A面
            setComposition($('#show_details').data("a"));
            return;
        }
        if(id == 'b0') {//B面
            setComposition($('#show_details').data("b"));
            return;
        }
        var _data = $('#show_details').data(id)  ;
        var category = _data['category'];
        var quantity = _data['quantity'];
        buildTerminal(id,category,quantity);
    }


    /**
     *任务添加中，中间区域显示端子信息
     * @param treeId  为分区ID
     * @param category  为槽和端子排列方式
     * @param quantity   槽数量
     * @param style   0:不可选择。1:多选（建熔纤、排障、其他等任务时使用）。2:主干端子单选、配线端子多选（建跳纤等任务时使用）
     * @param isClick  是否点击
     */
    function buildTerminalContent(treeId,category,quantity,style,isClick){
        if(!style) {
            style = 0;
        }
        isClick = false;
        var obj = {};
        switch(category){
            case 'HORIZONTAL_TOP2BOTTOMatTERMINAL_LEFT2RIGHT':  //横排（盘列自上而下，端子自左而右）
                obj = {id:treeId,hv:'H',num:quantity,caoNum:0,sort:0,layout:style,showTit:false,click:isClick}
                break;
            case 'HORIZONTAL_TOP2BOTTOMatTERMINAL_RIGHT2LEFT': //横排（盘列自上而下，端子自右而左）
                obj = {id:treeId,hv:'H',num:quantity,caoNum:0,sort:1,layout:style,showTit:false,click:isClick}
                break;
            case 'HORIZONTAL_BOTTOM2TOPatTERMINAL_LEFT2RIGHT':  //横排（盘列自下而上，端子自左而右）
                obj = {id:treeId,hv:'H',num:quantity,caoNum:1,sort:0,layout:style,showTit:false,click:isClick}
                break;
            case 'HORIZONTAL_BOTTOM2TOPatTERMINAL_RIGHT2LEFT': //横排（盘列自下而上，端子自右而左）
                obj = {id:treeId,hv:'H',num:quantity,caoNum:1,sort:1,layout:style,showTit:false,click:isClick}
                break;
            case 'VERTICAL_LEFT2RIGHTatTERMINAL_TOP2BOTTOM':// 竖排（盘自左而右，端子自上而下）
                obj = {id:treeId,hv:'V',num:quantity,caoNum:0,sort:0,layout:style,showTit:false,click:isClick}

                break;
            case 'VERTICAL_LEFT2RIGHTatTERMINAL_BOTTOM2TOP': //竖排（盘自左而右，端子自下而上）
                obj = {id:treeId,hv:'V',num:quantity,caoNum:0,sort:1,layout:style,showTit:false,click:isClick}
                break;
            case 'VERTICAL_RIGHT2LEFTatTERMINAL_TOP2BOTTOM':// 竖排（盘自右而左，端子自上而下）
                obj = {id:treeId,hv:'V',num:quantity,caoNum:1,sort:0,layout:style,showTit:false,click:isClick}
                break;
            case 'VERTICAL_RIGHT2LEFTatTERMINAL_BOTTOM2TOP': //竖排（盘自右而左，端子自下而上）
                obj = {id:treeId,hv:'V',num:quantity,caoNum:1,sort:1,layout:style,showTit:false,click:isClick}
                break;
        }
        return obj;
    } ;

    /**
     * 生成端子,同时将端子状态通过样式显示
     * @param treeId 区块ID
     * @param category  为槽和端子排列方式
     * @param quantity   槽数量
     */
    function buildTerminal(treeId,category,quantity){
        var obj =  buildTerminalContent(treeId,category,quantity)
        var deviceId = $('.select-composition').data("deviceId");
        var url = $('#getTerminalUrl').val();
        //获取端子状态
        $.getJSON(url,{deviceId:deviceId,area:treeId,r:Math.random()},function(data){
            $('#show_details_terminal_content').occ(obj,data);
        })

    }

    /**
     * 任务中，生成端子根据状态生成不同的样式,有选择进行标识
     * @param treeId 区块ID
     * @param category  为槽和端子排列方式
     * @param quantity   槽数量
     */
    function buildTerminal1(treeId,category,quantity){
        var obj =  buildTerminalContent(treeId,category,quantity,1)
        var deviceId = $('.select-composition').data("deviceId");
        var url = $('#getTerminalUrl').val();
        $.getJSON(url,{deviceId:deviceId,area:treeId,r:Math.random()},function(data){
            $('#task_details_content').occ(obj,data);
            var terminalArray = $('#task_dg').data('terminals');//已经选择的端子
            if(terminalArray && terminalArray.length > 0){
                for(var i=0;i<terminalArray.length;i++){
                    $("#task_details_content input[value='"+terminalArray[i]+"']").attr("checked",true); //选中
                }
            }
        })
    }

    /**
     * 任务在熔钎，右边内容.
     */
    function taskRqRightHtml() {
        var _result = "<div style='padding: 3px;'><p>光缆段名称：<input type=\"text\" name=\"opticalcableName\"/></p>" ;
            _result += "光蕊序列：从<input type=\"text\" name=\"opticalcableCodeStart\" style='width:50px;' />" ;
            _result +=  "到<input type=\"text\" name=\"opticalcableCodeEnd\" style='width:50px;' />" ;
            _result +=  "<p>方向：<input type=\"radio\" name=\"direction\" value='1' checked='true' />上行端<input type=\"radio\" name=\"direction\" value='2' />上行端" ;
            _result +=  "</p></div>" ;
           // _result +=  "<div><input type=\"button\" name=\"taskBtn\" value=\"设定\"/></div>" ;
        return _result;
    }

    /**
     * 任务，跳纤右边内容
     */
    function taskTqRightHtml() {
        var _result = "<div style='padding:3px;'>配对端子<textarea rows=\"13\" cols=\"13\" name=\"pair\" ></textarea></div>";
        return _result;
    }

    //端子标签中布局树形结构
    $('#show_details_terminal_tree').tree({
        data:[]    ,
        onClick: function(node){
            var id = node.id;
            treeNodeClick(id);
        }
    });



    /**
     * {"id":1,"name":"aa55","description":"aaa",
     * "composition_a":"c_1_1","composition_b":"c_2_1",
     * "b1":{"category":"VERTICAL_LEFT2RIGHT","quantity":2},
     * "b2":{"category":"VERTICAL_RIGHT2LEFT","quantity":3},
     * "a1":{"category":"HORIZONTAL_TOP2BOTTOM","quantity":1}
     * @param map 解析这种格式转化成页面.
     */
    function build(map) {
        if(map && map.id) {

            buildTree(buildTreeData(map));

        }

    }

    /**
     * 生成树形需要的数据格式.
     *
     * @param map 后台返回的格式
     */
    function buildTreeData(map) {
        var aname = map.composition_a;
        var bname = map.composition_b;
        var anames = aname.split('_');
        var bnames;
        var acount = anames[1];
        var bcount = 0;
        var treeDataA = [acount];
        var treeDataB = [];
        if(bname) {
            bnames = bname.split('_');
            bcount = bnames[1];
            treeDataB = [bcount];
        }
        var treeData = [2] ;
        $('#show_details').data("a",aname);//A区,布局名称
        $('#show_details').data("b",bname); //B区,布局名称

        for(var i=1;i<=acount;i++){
            var _data = map['a'+i];
            $('#show_details').data('a'+i,_data); //a区块，对应的数据如：a1:{category:'',quantity:1}
            treeDataA[i-1]={id:'a'+i,text:'机框'+i}
        }
        for(var i=1;i<=bcount;i++){
            var _data = map['b'+i];
            $('#show_details').data('b'+i,_data); //b区块，对应的数据如：a1:{category:'',quantity:1}
            treeDataB[i-1]={id:'b'+i,text:'机框'+i}
        }
        if(!treeDataB)  {
            treeDataB = [];
        }
        treeData[0] = {id:'a0',text:'A面',children:treeDataA};
        if(treeDataB && treeDataB.length > 0){
            treeData[1] = {id:'b0',text:'B面',children:treeDataB};
        }
        return treeData;
    }

    //生成树
    function buildTree(treedata) {
        var _tree = $('#show_details_terminal_tree') ;
        /*var node = _tree.tree('getRoot');
        var children = _tree.tree('getChildren', node?node.target:null);
        for(var i=0; i<children.length; i++){
            _tree.tree('remove', children[i].target);
        }

        _tree.tree('append',{
            parent: (node?node.target:null),
            data:treedata
        });*/
        _tree.tree({
            data:treedata
        });
    }

    /**
     * 任务中需要的树
     * @param treedata
     */
    function buildTree1(treedata) {
        var _tree = $('#task_details_tree') ;
       /* var node = _tree.tree('getRoot');
        var children = _tree.tree('getChildren');
        for(var i=0; i<children.length; i++){
            _tree.tree('remove', children[i].target);
        }*/
        _tree.tree({
            data:treedata ,
            onClick: _taskTreeClick
        });
    }

    //任务中树的节点点击
    function _taskTreeClick(node) {
        var id = node.id;
        var _data = $('#show_details').data(id)  ;
        if(!_data) {
            return;
        }
        var _taskStatus = $('#task_status').val();
        var category = _data['category'];
        var quantity = _data['quantity'];
        if(_taskStatus == 'MELTING') {
            buildTerminal1(id,category,quantity)
        }
    }

    //端子标签中，生成端子排列内容.
    function buildContent(content) {
        $("#show_details_terminal_content").html(content) ;
    }

    //任务中，，生成端子排列内容.
    function buildTaskContent(content) {
        $("#task_details_content").html(content) ;
    }

    //生成任务中右边区域的内容.
    function buildTaskRight(content) {
        $("#task_dtails_right").html(content) ;
    }



    //布置布局
    function setComposition(name) {
        var url = $("#compositionUrl").val()  ;
        var _content = $("#compositionUrl").data(name)   ;
        if(_content) {
            buildContent(_content) ;
            return;
        }
        $.get(url,{name:name,r:Math.random()},function(data){
            buildContent(data)   ;
            $("#compositionUrl").data(name,data)
        })
    }

    //任务添加或编辑确定，form提交
    function okHandler(){
        $('#add_task_form').form('submit',{
            onSubmit: function(){
                var taskDetaLayoutShow = $('#task_deta_layout:visible') ;
                if(taskDetaLayoutShow && taskDetaLayoutShow.length > 0) {
                    var opticalcableName = $("#task_dg input[name='opticalcableName']");
                    var opticalcableCodeStart = $("#task_dg input[name='opticalcableCodeStart']");
                    var opticalcableCodeEnd = $("#task_dg input[name='opticalcableCodeEnd']");
                    var direction = $("#task_dg input[name='direction']") ;
                    var pair = $("#task_dg textarea[name='pair']");
                    var deviceId = $("#task_dg input[name='device.id']");
                    var terminal = $("#task_dg input[name='terminal']") ;
                    var tastType = $("#task_dg input[name='task_status']") ;

                    if(deviceId && deviceId.val() == '') {
                        $.messager.alert('提示','选择正确的设备','info');
                        return false;
                    }

                    if(tastType == 'MELTING' && terminal && terminal.val() == '') {
                        $.messager.alert('提示','请选择端子','info');
                        return false;
                    }

                    if(opticalcableName && opticalcableName.val() == '') {
                        $.messager.alert('提示','填写正确的光缆段名称','info');
                        return false;
                    }

                    if(opticalcableCodeStart && opticalcableCodeStart.val() == '') {
                        $.messager.alert('提示','填写正确的光蕊序号开始','info');
                        return false;
                    }

                    if(opticalcableCodeEnd && opticalcableCodeEnd.val() == '') {
                        $.messager.alert('提示','填写正确的光蕊序号结束','info');
                        return false;
                    }

                    if(pair && pair.val() == '')  {
                        $.messager.alert('提示','填写正确的配对端子','info');
                        return false;
                    }
                }
                return $(this).form('validate');
            },
            success: function(data) {
                var data = eval('('+data+')');
                if (data.status == '1'){
                    $('#task_dg').dialog('close');      // close the dialog
                    $('#task_uncomplete').datagrid('reload')
                } else {
                    $.messager.show({
                        title: 'Error',
                        msg: data.msg
                    });
                }
            }

        });
    }

    //任务，跳纤根据点击的端子，生成右边配对信息.
    function tiaoQianPair(ele) {
        var pair = $("#task_dg textarea[name='pair']");
        var pairVal = pair.val();
       var t = $(ele);
        var pp = t.parent().parent();
        if(!pp.hasClass('px') && !pp.hasClass('zg')){
            return;
        }
        if(t.attr("type") == 'radio') {
            if(pairVal) {
                var i = pairVal.indexOf('|');
                if(i !=-1) {
                    pairVal = pairVal.substr(i);
                    pair.val(t.val()+pairVal);
                } else{
                    pair.val(t.val());
                }
            } else{
                pair.val(t.val());

            }
            return;
        }
        if(!pairVal || pairVal == '') {
             return;
        }
        var chked = t.attr('checked');
        var i = pairVal.indexOf('|');
        if(i == -1) {
            if(chked) {
                pair.val(pairVal+'|'+t.val())
            }
            return;
        }
        if(chked) {
            var _l = pairVal.length;
            if((_l-1) == i ){
                pair.val(pairVal+t.val())
            }else{
                pair.val(pairVal+','+t.val())
            }
        }else{
            var _vs = pairVal.split('|') ;
            var _pxs = _vs[1].split(',');
            var _i = $.inArray(t.val(),_pxs);
            if(_i !=-1) {
                _pxs.splice(_i,1);
                if(_pxs.length == 0) {
                    pair.val(_vs[0]);
                }else{
                    pair.val(_vs[0]+'|'+_pxs.toString());
                }
            }
        }
    }

    //任务，点击所有端子，主要 是熔纤和条纤
    $("#task_dg .cr").live('click',function(){
        var type = $("#task_dg select[name='task_status']").val();

        if(type == 'JUMPING') {
            tiaoQianPair(this);
            return;
        }

        var terminalArray = $('#task_dg').data('terminals');
        if(!terminalArray) {
            terminalArray = new Array();
        }
        var val = $(this).val();
        var chked = $(this).attr("checked") ;
        var index = $.inArray(val,terminalArray);
        if(chked) {
            if(index == -1) {
                terminalArray.push(val);
            }
        }else {
            if(index >= 0) {
                terminalArray.splice(index,1);
            }
        }
        $('#task_dg').data('terminals',terminalArray);
        $("#task_dg input[name='terminal']").val(terminalArray.toString())
    }) ;

    //添加任务
    function lstAdd(){
        $('#task_dg').dialog('open');
        $('#add_task_form').form("clear");
        _taskDetailContent();
        var d = new Date();
        $('#assignDate').datebox('setValue', d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate());
        $('#task_dg').removeData('terminals');
    }
    //编辑任务
    function lstUpdate() {
        $('#task_dg').dialog('open');
        $('#add_task_form').form("clear");
        var selected = $('#task_uncomplete').datagrid("getSelected");
        $('#add_task_form').form("load",selected);
        _taskDetailContent();
        $("#task_dg input[name='opticalcableName']").val(selected.opticalcableName);
        $("#task_dg input[name='opticalcableCodeStart']").val(selected.opticalcableCodeStart);
        $("#task_dg input[name='opticalcableCodeEnd']").val(selected.opticalcableCodeEnd);
        $("#task_dg input[name='direction']").val(selected.direction);
        $("#task_dg textarea[name='pair']").val(selected.pair);
        $("#task_description").val(selected.description);
        var _ter =  selected.terminal;
        if(_ter ) {
            _ter = _ter.split(',');
            if(_ter.length > 0) {
                $('#task_dg').data('terminals',_ter);
            }
        }
    }
    //删除任务
    function lstDelete(){
        var row = $('#task_uncomplete').datagrid('getSelected');
        if (row){
            $.messager.confirm('提示','确定删除该记录?',function(r){
                if (r){
                    $.post($('#taskDeleteUrl').val(),{id:row.id},function(result){
                        if (result.status == '1'){
                            $('#task_uncomplete').datagrid('reload'); // reload the user data
                        } else {
                            $.messager.show({ // show error message
                                title: 'Error',
                                msg: result.msg
                            });
                        }
                    },'json');
                }
            });
        }
    }

    //添加任务，选择类型.
    $('#task_status').change(function(){
        _taskDetailContent();
    })  ;

    //添加任务，根据不同类型生成弹出窗口的内容
    function _taskDetailContent(){
        var status = $('#task_status').val() ;
        var deviceId = $('.select-composition').data("deviceId");
        $("#task_dg input[name='device.id']").val(deviceId);
        if(status == 'MELTING' || status == 'JUMPING') {
            //var content = $('#rongqian').val();
            //$('#task_deta').html(content);
            $('#task_description').hide();
            $('#task_deta_layout').show();
            var data = $('.select-composition').data("deviceComposition");
            buildTree1(buildTreeData(data));
        }
        if(status == 'MELTING') {
            buildTaskRight(taskRqRightHtml());
            buildTaskContent('');
        }
        if(status == 'JUMPING') {
            buildTaskRight(taskTqRightHtml());
            buildTaskContent('');
            tiaoqian();
        }
        if(status == 'TROUBLESHOOTING' || status == 'OTHER') {
           // $('#task_deta_layout').layout('panel','west').close(true);
            //var content = "<textarea rows=\"5\" cols=\"30\" name=\"description\"></textarea>";
            //$('#task_deta').html(content);
            $('#task_description').show();
            $('#task_deta_layout').hide();
        }
        if(status == 'OTHER') {
           // var content = "<textarea rows=\"5\" cols=\"30\" name=\"description\"></textarea>";
            ///$('#task_deta').html(content);
        }
    }

    //任务，跳纤内容
    function tiaoqian() {

        var s = "<div id='task_content_tabs' style='height: 240px;'></div>"
        buildTaskContent(s);

        var map = $('.select-composition').data("deviceComposition") ;

        $('#task_details_content #task_content_tabs').tabs({
            onSelect:function(title){
                var _data = map[title];
                var category = _data['category'];
                var quantity = _data['quantity'];
                tiaoQianBuildTerminal1("task_content_tabs_t_"+title+"",title,category,quantity);
            }
        });

        var aname = map.composition_a;
        var bname = map.composition_b;
        var anames = aname.split('_');
        var bnames;
        var acount = anames[1];
        var bcount = 0;
        if(bname) {
            bnames = bname.split('_');
            bcount = bnames[1];
        }
        for(var i=1;i<=acount;i++)  {
            var tit = 'a'+i;
            var obj = {
                title:tit,
                content:"<div  style='padding:5px;' id='task_content_tabs_t_"+tit+"'></div>"
            }
            $('#task_content_tabs').tabs('add',obj);
        }

        for(var j=1;j<=bcount;j++)  {
            var tit = 'b'+j;
            var obj = {
                title:tit,
                content:"<div  style='padding:5px;' id='task_content_tabs_t_"+tit+"'></div>"
            }
            $('#task_content_tabs').tabs('add',obj);
        }
    }


    /**
     * 任务，跳纤类型中的端子生成
     * @param ele 端子生成的区域id
     * @param treeId 区块id
     * @param category //槽排列
     * @param quantity  //槽数量
     */
    function tiaoQianBuildTerminal1(ele,treeId,category,quantity){
        var obj =  buildTerminalContent(treeId,category,quantity,2)
        var deviceId = $('.select-composition').data("deviceId");
        var url = $('#getTerminalUrl').val();
        var _r =  $("#task_dg textarea[name='pair']").val();
        $.getJSON(url,{deviceId:deviceId,area:treeId,r:Math.random()},function(data){
            $("#"+ele+"").occ(obj,data);
            if(_r) {
                var _rs = _r.split('|');
                $("#task_details_content input[value='"+_rs[0]+"']").attr("checked",true);
                var _pxs = _rs[1].split(',');
                for(var i=0; i<_pxs.length; i++) {
                    $("#task_details_content input[value='"+_pxs[i]+"']").attr("checked",true);
                }

            }
        })
    }

    //在端子标签中，设定端子的详细
    $('.save-terminal-btn').live('click',function(){
        var _tree = $('#show_details_terminal_tree').tree('getSelected') ;
        var deviceId = $('.select-composition').data("deviceId");
        if(!_tree || !deviceId) {
            return;
        }

        var id = _tree.id;
        var terval = $("#terminal_detail_container input[name='terId']").val();// $("input[name='okaysoft_checkbox_"+id+"']:checked");
        var terNumber = $("#terminal_detail_container input[name='number']").val();
        var deviceName = $("#terminal_detail_container input[name='deviceName']").val();
        var deviceTerminal = $("#terminal_detail_container input[name='deviceTerminal']").val();
         /*var terval = '';

        ters.each(function(){
            if(terval) {
                terval += ',';
            }
            terval += $(this).val();
        })
         $("#terminal_detail_container input[name='terId']").val(terval);*/
        $("#terminal_detail_container input[name='area']").val(id);
        $("#terminal_detail_container input[name='device.id']").val(deviceId);
       $('#add_terminal_form').form('submit',{
            onSubmit: function(){
                if(terval == '') {
                    $.messager.alert('提示','没有选择端子','info');
                    return false;
                }
                if(!terNumber || terNumber == ''){
                    $("#terminal_detail_container input[name='number']").focus();
                    $.messager.alert('提示','端子编号不能为空','info');
                    return false;
                }
                if(deviceName == '' && deviceTerminal !='') {
                    $.messager.alert('提示','输入上级端子箱子名称','info');
                    return false;
                }
                if(deviceTerminal == '' && deviceName!='') {
                    $.messager.alert('提示','输入上级端子端子编号','info');
                    return false;
                }

                return $(this).form('validate');
            },
            success:function(data){
                var data = eval('('+data+')');
                if (data.status == '1'){
                    $.messager.alert('提示','设定成功','info');
                    var form = $("form.add_terminal_form");
                    var tf = form.find("input[name='id']");
                    tf.val(data.tid)
                    var _data = $('#show_details').data(id)  ;
                    var category = _data['category'];
                    var quantity = _data['quantity'];
                    buildTerminal(id,category,quantity);
                } else if(data.status == '2'){
                    $.messager.alert('提示','上级端子的设备名称和端子编号不对应','info');
                }else{
                    $.messager.alert('提示','设定失败,编号已经存在！','info');
                }
            }
        });
    }) ;

    //在端子标签中，点击每个端子
    $('#show_details_terminal_content .img1,#show_details_terminal_content .img2').live('click',function(){
        var t = $(this);
        $('.img1').removeClass('img2');
        $("#terminal_detail_container").html("<span>loading...</span>");
        $("#terminal_detail_container #add_terminal_form").hide();
        $("#terminal_detail_container #device_terminal_show_container").show();
        t.addClass('img2')
       // var chked = $(this).attr('port_caption');
        //if(!chked) {
        //    return;
       // }
        var _tree = $('#show_details_terminal_tree').tree('getSelected') ;
        var deviceId = $('.select-composition').data("deviceId");
        var terId = $(this).attr('port_caption');
        var terIds = terId.split("_");
        $("#add_terminal_form .splitter-chk").hide();
        //$("#add_terminal_form .superior-terminal").hide();
        var url = $("#terminalObjUrl").val();
        $("#terminal_detail_container").load(url,{area:_tree.id,deviceId:deviceId,terId:terId,r:Math.random()}) ;
        /*$.getJSON(url,{area:_tree.id,deviceId:deviceId,terId:terId},function(data){
            if(data){
                if(data.status){
                    data.status = data.status.name;
                }
                if(data.backboneWiring){
                    data.backboneWiring = data.backboneWiring.name;
                }
                if(data.device) {
                    data['device.id'] = data.device.id;
                }

                $('#add_terminal_form').form('load',data);
                $("#terminal_detail_container input[name='opening']").attr("checked",data.opening);
                //$("#terminal_detail_container input[name='vip']").attr("checked",data.vip);
                $("#terminal_detail_container input[name='splitter']").attr("checked",data.splitter);
                if(data.backboneWiring == 'BACKBONE') {
                    $("#add_terminal_form .superior-terminal").show();
                } else{
                    $("#add_terminal_form .superior-terminal").hide();
                }
                if(data.splitter){
                    $("#add_terminal_form .splitter-chk").show();
                } else{
                    $("#add_terminal_form .splitter-chk").hide();
                }
                _setTerminalDetails(data)
            } else {
                _setTerminalDetails({'number':terId,'letter':terIds[1],'letterNumber':terIds[2]})  ;
                $('#add_terminal_form').form('clear')  ;
                $("#terminal_detail_container input[name='terId']").val(terId);
                $("#terminal_detail_container input[name='device.id']").val(deviceId);
                $("#terminal_detail_container input[name='number']").val(terId);
                $("#terminal_detail_container input[name='letter']").val(terIds[1]);
                $("#terminal_detail_container input[name='letterNumber']").val(terIds[2]);
            }
        }) */
    }) ;

    function _setTerminalDetails(data) {
        var container = $("#device_terminal_show_container");
        container.find("#t_number").html(data.number);
        container.find("#t_letter").html(data.letter);
        container.find("#t_letterNumber").html(data.letterNumber);
        container.find("#t_code").html(data.code);
        container.find("#t_logo").html(data.logo);
        container.find("#t_status").html(data.statusName);
        container.find("#t_opening").html(data.opening=='1'?'是':'否');
        container.find("#t_segmentName").html(data.segmentName);
        container.find("#t_opticalNumber").html(data.opticalNumber);
        container.find("#t_backboneWiring").html(data.backboneWiringName);
        container.find("#t_clientUser").html(data.client_combo);
        container.find("#t_businessType").html(data.businessType);
        container.find("#t_splitter").html(data.splitter=='1'?'有':'无');
        if(data.splitter=='1')  {
            container.find("#t_splitterModel").parent().show()
            container.find("#t_splitterModel").html(data.splitterModel);
            container.find("#t_splitRatio").parent().show();
            container.find("#t_splitRatio").html(data.splitRatio);
            container.find("#t_opticalSplitterPorts").parent().show();
            container.find("#t_opticalSplitterPorts").html(data.opticalSplitterPorts);
        }
        if(data.backboneWiring == 'BACKBONE'){
            container.find("#t_superiorTerminal").parent().show();
            container.find("#t_superiorTerminal").html(data.superiorTerminal);
        }
        container.find("#t_jumperPort").html(data.jumperPort);

        container.find("#t_description").html(data.description);
        container.find("#t_vip").html(data.vip=='1'?'是':'否');
    }

    //地理标签中，地图生成
    function initMap() {
        var loca = $('.select-composition').data("location");
        if(!loca) {
            setTimeout(initMap, 1000);
            return;
        }
        var _latitude = parseFloat(loca.latitude);
        var _longitude = parseFloat(loca.longitude);
        var map = new BMap.Map("device_map");
        var point = new BMap.Point(_longitude,_latitude);
        map.centerAndZoom(point, 15);

        // 地图平移缩放控件
        map.addControl(new BMap.NavigationControl());
        // 比例尺控件
        map.addControl(new BMap.ScaleControl());
        // 缩略地图控件
        map.addControl(new BMap.OverviewMapControl());
        var marker = new BMap.Marker(point);
        map.addOverlay(marker);
    }

    //任务标签
    function task() {
        var url = $('#taskStatusUrl').val();
        var deviceId = $('.select-composition').data("deviceId");

        if(!deviceId){
            deviceId='';
        }
        //已经完成
        $('#task_complete').datagrid({
            url:url+"?status=COMPLETE&deviceId="+deviceId+"&r="+Math.random(),
            singleSelect:true,
            idField:'id',
            columns:[[
                {field:'type',title:'类型',width:100},
                {field:'description',title:'任务描述',width:150},
                {field:'result',title:'处理情况',width:150},
                {field:'completeDate',title:'处理人/完成时间',width:120}
            ]],
            onBeforeLoad:function(){
                $(this).datagrid('rejectChanges');
            },
            pagination:true,
            rownumbers:true
        });
        //未完成
        $('#task_uncomplete').datagrid({
            url:url+"?status=NOTCOMPLETE&deviceId="+deviceId,
            singleSelect:true,
            idField:'id',
            columns:[[
                {field:'type',title:'类型',width:100},
                {field:'description',title:'任务描述',width:300}

            ]],
            onBeforeLoad:function(){
                $(this).datagrid('rejectChanges');
            },
            onClickRow:function(rowIndex,rowData) {
                $('#show_task_details_tab #btnedit').linkbutton('enable');
                $('#show_task_details_tab #btnremove').linkbutton('enable');

            },
            pagination:true,
            rownumbers:true,
            toolbar:[{
                id:'btnadd',
                text:'添加',
                iconCls:'icon-add',
                handler:lstAdd
            },{
                id:'btnedit',
                text:'编辑',
                disabled:true,
                iconCls:'icon-edit',
                handler:lstUpdate
            },'-',{
                id:'btnremove',
                text:'删除',
                disabled:true,
                iconCls:'icon-remove',
                handler:lstDelete
            }]
        });
    }

    var callback =  function(data){
        if(!data) {
            return;
        }
        $('.select-composition').data("location",{latitude:data.latitude,longitude:data.longitude}) ;

        $('.select-composition').removeData("deviceComposition") ;
        //$('#cc').combotree('setValue', '');

        if(data && data.id) {
            $('.select-composition').data(""+data.id,data) ;
            $('.select-composition').data("deviceComposition",data) ;
            //$('#cc').combotree('setValue', data.id);
        }
        build(data)
    } ;

    /**
     * 端子生成，窗口需要的数据生成.
     * @param deviceId
     */
    function init(deviceId) {
        $('#show_details_terminal_formwork').show();
        $('#show_details_terminal_content').hide();
        $('.select-composition').data("deviceId",deviceId);
        var url = $('#terminalUrl').val();
        $.getJSON(url,{id:deviceId,r:Math.random()},callback)  ;

        //设备详情
        var url = $('#deviceUrl').val()  ;
        url += "?id="+deviceId+"&r="+Math.random();
        $('#show_details_tab_gy').load(url) ;

        //任务数据初始
        task();

        //地理位置
        initMap();
    }

    //在任务管理中点击
    $('.task_show_detail').live('click',function(){
        $('#show_details').dialog("open");
        var datag = $('#task_tb').datagrid('getSelected');
        var id = datag['device.id'];
        init(id);
        $('#show_details_tab').tabs('select','任务管理');
    }) ;

    //在设备管理中点击
    $('.device_selected_cla').live('click',function(){
        $('#show_details').dialog("open");
        var datag = $('#client_tab').datagrid('getSelected');
        var id = datag['id'];
        init(id);
    })  ;

});